package com.velvetantler.weather.utils

import com.velvetantler.weather.WeatherApplication
import com.velvetantler.weather.api.ApiServices
import com.velvetantler.weather.constants.Constants
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory

object RetrofitClient {

    private const val BASE_URL = "http://172.20.208.1:3000/"

    /**
     * token拦截器
     */
    private class RequestInterceptor() : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {

            val token =
                PreferenceUtil.getInstance(
                    WeatherApplication.getGlobalContext()!!.applicationContext
                ).getValue(Constants.TOKEN_PREF_KEY)

            var request = chain.request()
            if (!token.isNullOrEmpty()) {
                request = request.newBuilder()
                    .addHeader("Authorization", "Bearer $token")
                    .build()
            }
            return chain.proceed(request)
        }
    }

    /**
     * 响应拦截器
     */
    private class ResponseInterceptor() : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val response = chain.proceed(chain.request())

            return response
        }
    }

    /**
     * 创建OkHttpClient实例
     */
    private val okHttpClient: OkHttpClient by lazy {
        OkHttpClient.Builder()
            .addInterceptor(RequestInterceptor()) // 添加token拦截器
            .addInterceptor(ResponseInterceptor())
            // 添加日志拦截器，用于打印请求和响应的详细信息（调试时非常有用）
            .addInterceptor(HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY // 打印完整的请求和响应内容
            })
            .build()
    }

    /**
     * 创建Retrofit实例
     */
    val apiServices: ApiServices by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(okHttpClient) // 设置OkHttpClient实例
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(ApiServices::class.java)
    }
}